package com.example.nonggo.api;

import android.text.TextUtils;
import android.util.Log;


import com.allen.library.base.BaseObserver;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.example.nonggo.bean.MBaseData;
import com.example.nonggo.utils.CustomToastUtils;

import io.reactivex.disposables.Disposable;

/**
 * Created by Allen on 2017/10/31.
 *
 * @author Allen
 * <p>
 * 针对特定格式的时候设置的通用的Observer
 * 用户可以根据自己需求自定义自己的类继承BaseDataObserver<T>即可
 * 适用于
 * {
 * "code":0,
 * "msg":"成功"
 * "data":{
 * "userName":"test"
 * "token":"abcdefg123456789"
 * "uid":"1"}
 * }
 */

public abstract class MDataObserver<T> extends BaseObserver<MBaseData<T>> {


    private final String TAG = "MDataObserver";

    /**
     * 成功回调
     *
     * @param data 结果
     */
    protected abstract void onSuccess(T data);

    @Override
    protected boolean isHideToast() {
        return true;
    }

    @Override
    public void doOnSubscribe(Disposable d) {
    }

    @Override
    public void doOnError(String errorMsg) {
        if (!isHideToast() && !TextUtils.isEmpty(errorMsg)) {
            if (!errorMsg.equals("解析错误")) {
                Log.e(TAG, "doOnError: " + errorMsg);
                onError();
            }
        }
    }

    @Override
    public void doOnNext(MBaseData<T> data) {
        //可以根据需求对code统一处理
        if (data.getResult() == 0) {
            onSuccess(data.getData());
        } else {
            apiError(data.getMessage());
            onErrorMsg(data.getResult(), data.getMessage());
            onError();
        }
    }

    @Override
    public void doOnCompleted() {

    }

    /**
     * @param errorMsg 错误信息
     */
    private void apiError(String errorMsg) {
        CustomToastUtils.showCustomToast(errorMsg);
        Log.e(TAG, "api error: " + errorMsg);
    }

    //如果需要错误回调，复写此方法
    protected void onError() {

    }

    //如果需要错误回调，复写此方法
    protected void onErrorMsg(int errorCode, String errorMsg) {
        CustomToastUtils.showCustomToast(errorMsg);
    }
}
